import express from 'express'
import { WebSocketServer } from 'ws'
import { createServer } from 'http'
import { fileURLToPath } from 'url'
import path from 'path'
/* 中间件 */
import loggerMiddleware from './middleware/logger.js'
import { preventHotLinking } from './middleware/preventHotLinking.js'
/* 路由模块 */
import user from './router/user.js'
import system from './router/system.js'
import event from './router/event.js'
import util from './router/util.js'
import ffmpeg from './router/ffmpeg.js'
import jsdom from './router/jsdom.js'
import pngquant from './router/pngquant.js'
import fs from './router/fs.js'
import crypto from './router/crypto.js'
import tem from './router/tem.js'
import zlib from './router/zlib.js'
import http from './router/http.js'
import reverseProxy from './router/reverse-Proxy.js'
import mime from './router/mime.js'
import mailer from './router/mailer.js'
import hotlinking from './router/Hotlinking.js'

// import {loadSrc} from './utils/readSrc.js'
// console.log(loadSrc())

const app = express()
app.set('view engine', 'ejs') // 设置模板引擎为 EJS

app.use(loggerMiddleware)
app.use(preventHotLinking) // 应用防止热链中间件

// 初始化静态资源目录 express.static
// app.use(express.static('public'))
app.use('/assets', express.static('public')); // 处理静态资源请求

app.use(express.json()) //获取请求体

app.use('/user', user)
app.use('/system', system)
app.use('/event', event)
app.use('/util', util)
app.use('/ffmpeg', ffmpeg)
app.use('/jsdom', jsdom)
app.use('/pngquant', pngquant)
app.use('/fs', fs)
app.use('/crypto', crypto)
app.use('/tem', tem)
app.use('/zlib', zlib)
app.use('/http', http)
app.use('/reverseProxy', reverseProxy)
app.use('/mime', mime)
app.use('/mailer', mailer)
app.use('/hotlinking', hotlinking)

// 配置静态文件目录
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
// path.join(__dirname, )
console.log(__dirname, __filename)
// 然后你可以使用__dirname和__filename作为路径相关的变量


app.get('/', (req, res) => {
  res.render('index', { title: 'ejs demo' }) // 渲染 index 模板，并传递 title 数据
})

const server = createServer(app)
const wss = new WebSocketServer({ server })

wss.on('connection', function connection(ws) {
  console.log('WebSocket连接已建立')
  ws.on('message', function incoming(message) {
    console.log('收到消息：', message)
    ws.send(JSON.stringify({ msg: '已收到消息：' + message })) // 发送回客户端消息
  })
})

server.listen(3001, function listening() {
  console.log('WebSocket服务已启动，监听端口：', 3001)
})
